/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet.tetris;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import sirtet.Player;
import sirtet.event.PlayerActionEvent;
import sirtet.event.PlayerEvent;
import sirtet.event.PlayerListener;
import sirtet.netplay.ClientResponse;

/**
 * This listener parses action message triggered by a player and transform it
 * into an attack to the local board
 * @author guangwei.zhu
 */
public class ActionBattlingAttacker {

    private Player player;
    private Set<BattlingTetrisTarget> targets = new HashSet<BattlingTetrisTarget>();
    private PlayerListener listener = new PlayerListener() {

        public void actionPerformed(PlayerActionEvent evt) {
            if (targets == null || !evt.action.actor.equals(player.id())) {
                return;     // Nothing to do
            }
            String attack = ClientResponse.parse(BattlingTetrisBoard.MSG_ATTACK, evt.action.command);
            if (attack != null) {
                int len = attack.length();
                Object[][] line = new Object[1][len];
                for (int i = 0; i < len; i++) {
                    line[0][i] = Integer.valueOf(attack.substring(i, i + 1));
                }
                for (BattlingTetrisTarget target : targets) {
                    target.takeAttack(line);        // Notify all victims
                }
            }
        }

        public void playerQuit(PlayerEvent evt) {
            dispose();
        }

        public void playerEnabled(PlayerEvent evt) {
        }

        public void playerDisabled(PlayerEvent evt) {
        }

        public void playerReady(PlayerEvent evt) {
        }
    };

    public ActionBattlingAttacker(Player player) {
        this.player = player;
        player.addPlayerListener(listener);
    }

    /**
     * Register an attack target
     * @param target an attack target to which eliminated blocks will be sent
     */
    public void addAttackTarget(BattlingTetrisTarget target) {
        targets.add(target);
    }

    /**
     * Register a collection of attack targets
     * @param targets attack targets to which eliminated blocks will be sent
     */
    public void addAttackTargets(Collection<BattlingTetrisTarget> targets) {
        this.targets.addAll(targets);
    }

    /**
     * Remove all attack targets
     */
    public void clearAttackTarget() {
        targets.clear();
    }

    /**
     * Unregister an attack target
     * @param target an attack target to which eliminated blocks will be sent
     */
    public void removeAttackTarget(BattlingTetrisTarget target) {
        targets.remove(target);
    }

    public void dispose() {
        player.removePlayerListener(listener);
        player = null;
        targets = null;
    }
}
